package cn.ug.msg.mq;

import cn.ug.core.ensure.Ensure;
import cn.ug.msg.bean.SmsBean;
import cn.ug.msg.service.SmsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static cn.ug.config.QueueName.QUEUE_MSG_SMS_SEND;

/**
 * 消息接收
 * @author kaiwotech
 */
@Component
@RabbitListener(queues = QUEUE_MSG_SMS_SEND)
public class SmsReceiver {
    private Log log = LogFactory.getLog(SmsReceiver.class);
    private ObjectMapper mapper = new ObjectMapper();

    @Resource
    private SmsService smsService;

    @RabbitHandler
    public void process(Sms o) {
        try {

            log.info("SmsReceiver.process");
            log.info(mapper.writeValueAsString(o));

            if (null == o || StringUtils.isBlank(o.getPhone())) {
                Ensure.that(true).isTrue("00000002");
            }
            log.info("----短信发送中-----mobile="+o.getPhone());
            SmsBean smsBean = new SmsBean();
            smsBean.setType(o.getType());
            smsBean.setPhone(o.getPhone());
            smsBean.setParamMap(o.getParamMap());
            int res = smsService.send(smsBean);

            log.info("smsService.send res = " + res);
            if(res != 0) {

                log.error("短信发送失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
